package ru.spb.osll.myfit.fixtures;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import ru.spb.osll.myfit.fixtures.base.OneLineFixture;
import ru.spb.osll.myfit.util.MyFitProperties;

public class AppendLogFromTestWithIdFixture extends OneLineFixture {
  private static Logger log = Logger.getLogger(AppendLogFromTestWithIdFixture.class);
  private static Pattern LOG_NAME_PATTERN = Pattern.compile("([A-Za-z\\.0-9]*)_(.*)");
  
  public boolean appendLogFromTestWithIdAndLogFileName(String testId, String filename) throws Exception{
    appendLog(testId, filename);
    return true;
  }
  
  public boolean appendLogFromTestWithId(String testId) throws Exception{
    String logName = getLogNameByTestId(testId);    
    appendLog(testId, logName);
    return true;
  }
  
  
  private boolean appendLog(String testId, String filename) throws Exception{
    String resultsDirectory = getTestResultsDirectory();
    File logToAppend = new File(new File(resultsDirectory, testId), filename);
    if(!logToAppend.exists()){
      throw new Exception("Log file " + logToAppend.getAbsolutePath() + " doesn't exist");
    }
    
    log.info("Log from " + logToAppend.getName() + ":" );
    
    readFile(logToAppend);
      
    return true;
  }
  
  private void readFile(File file) throws IOException{
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new FileReader(file));
        String line;
        do {
            line = reader.readLine();
            if(line != null){
              log.info(line);
            }
        } while(line != null);
    } finally {
        if(reader != null) {
            try {
                reader.close();
            } catch(IOException e) {
                
            }
        }
    }
  }
  
  private String getLogNameByTestId(String testId){
    String logName = "";
    Matcher matcher = LOG_NAME_PATTERN.matcher(testId);
    if(matcher.find()){
      logName = matcher.group(1) + ".log";
    }
    return logName;
  }

  private String getTestResultsDirectory(){
    return new File(MyFitProperties.getTestDirectory()).getParent();
  }
  
  public static String[] getTestTableTemplates() {
    return new String[] {"|append log from test with id||"};
    // or |append log from test with id||and log file name|
  }
}
